package com.jams.goodox.activity.serve.tenement;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hangzhou.jin.customview.LoadView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.entity.PaymentBean;
import com.jams.goodox.entity.TenementMonthBean;
import com.jams.goodox.entity.TenementPayOrderBean;
import com.jams.goodox.entity.User;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

import static com.jams.goodox.utils.Utils.AddTwoValue;
import static com.jams.goodox.utils.Utils.SubtractTwoValue;

/**
 * 物业缴费年份列表
 * Created by jams_zhen on 2016/9/23.
 */

public class TenementYearActivity extends BaseActivity {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.img_check)
    ImageView imgCheck;
    @Bind(R.id.tx_chooseChild)
    TextView txChooseChild;
    @Bind(R.id.tx_needPay)
    TextView txNeedPay;
    @Bind(R.id.tx_address)
    TextView txAddress;
    @Bind(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;
    @Bind(R.id.load_view)
    LoadView load_view;

    private RecycleCommonAdapter recycleCommonAdapter;
    private List<PaymentBean.DataBean.YearPaymentBean> yearPaymentBeanList;

    private double addPrice = 0;//年总选中缴费金额
    private int chooseNum = 0;//年总选中缴费项
    private int allNum = 0;
    private double allPrice = 0;


    private String subId;

    private DecimalFormat decimalFormat;


    private int clickPosi;
    private String busId;
    private User user;


    @Override
    protected int getLayoutId() {
        return R.layout.tenement_year_list_activity;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "物业缴费查询");
        subId = getIntent().getStringExtra("subId");
        busId=getIntent().getStringExtra("busId");
        user=DataCacheManager.getInstance().getUser();

        decimalFormat = new DecimalFormat("#0.00");
        //金额标红
        txNeedPay.setText(Html.fromHtml("<font color=#666666>" + "合计：" + "</font>"
                + "<font color=#ff6e0b>" + "¥0.00" + "</font>"));

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        yearPaymentBeanList = new ArrayList<>();
        recycleCommonAdapter = new RecycleCommonAdapter<PaymentBean.DataBean.YearPaymentBean>(this, yearPaymentBeanList, R.layout.tenement_year_item) {
            @Override
            public void convert(RecycleCommonViewHolder helper, final PaymentBean.DataBean.YearPaymentBean item, final int position) {
                TextView tx_payItem = helper.getView(R.id.tx_payItem);//是否已缴费；代缴费项目及选中项目
                TextView tx_hasPay = helper.getView(R.id.tx_hasPay);//标注已校未交
                final TextView tx_year = helper.getView(R.id.tx_year);
                TextView tx_detail = helper.getView(R.id.tx_detail);
                ImageView img_check = helper.getView(R.id.img_check);
                TextView tx_payPrice = helper.getView(R.id.tx_payPrice);
                RelativeLayout rela_detail = helper.getView(R.id.rela_detail);
                RelativeLayout rela_payItem = helper.getView(R.id.rela_payItem);

                //之前此处要求，必须显示今年，去年，明年3年的物业缴费项，所以存在缴清不可选中的点击项
                if (item.getNeedPayNum() == 0) {//没有缴费项，灰显不可点击
                    tx_detail.setVisibility(View.GONE);
                    img_check.setVisibility(View.GONE);
                    tx_year.setTextColor(ContextCompat.getColor(TenementYearActivity.this, R.color.font_color_gray));
                    tx_hasPay.setBackgroundResource(R.drawable.bg_cancel_gray);
                    tx_payItem.setTextColor(ContextCompat.getColor(TenementYearActivity.this, R.color.font_color_gray));
                    rela_payItem.setClickable(false);
                    rela_detail.setClickable(false);
                } else {
                    tx_detail.setVisibility(View.VISIBLE);
                    img_check.setVisibility(View.VISIBLE);
                    tx_year.setTextColor(ContextCompat.getColor(TenementYearActivity.this, R.color.font_color_black));
                    tx_hasPay.setBackgroundResource(R.drawable.bg_cancel_theme);
                    tx_payItem.setTextColor(ContextCompat.getColor(TenementYearActivity.this, R.color.font_color_black));
                    rela_detail.setClickable(true);
                    rela_payItem.setClickable(true);
                }
                int year = Calendar.getInstance().get(Calendar.YEAR);
                int tagYear = item.getYear() - year;//去，今，明，必须加标注
                switch (tagYear) {
                    case -1:
                        item.setYearTitle("去年-" + item.getYear() + "年");
                        break;
                    case 0:
                        item.setYearTitle("今年-" + item.getYear() + "年");
                        break;
                    case 1:
                        item.setYearTitle("明年-" + item.getYear() + "年");
                        break;
                    default:
                        item.setYearTitle(item.getYear() + "年");
                        break;
                }
                tx_year.setText(item.getYearTitle());
                //是否勾选
                if (item.isChoose()) {
                    tx_payItem.setText(String.format("待缴：%s项  已选：%s项", item.getNeedPayNum(), item.getPreparePayNum()));//此处注意，NeedPayNum&PreparePayNum是用来表示当前选中缴费项，和缴费金额的
                    tx_payPrice.setVisibility(View.VISIBLE);
                    tx_payPrice.setText(Html.fromHtml("<font color=#666666>" + "合计：" + "</font>"
                            + "<font color=#ff6e0b>" + "¥" + decimalFormat.format(item.getPreparePay()) + "</font>"));
                    img_check.setImageResource(R.mipmap.check_theme);
                } else {
                    tx_payPrice.setVisibility(View.GONE);
                    img_check.setImageResource(R.mipmap.un_check_gray);
                    if (item.getNeedPayNum() == 0) {
                        tx_payItem.setText("已缴清");
                    } else {
                        tx_payItem.setText(String.format("待缴：%s项", item.getNeedPayNum()));
                    }
                }

                View.OnClickListener detailListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (Utils.isFastDoubleClick())
                            return;
                        clickPosi = position;
                        clickItem(item);
                    }
                };

                rela_detail.setOnClickListener(detailListener);
                rela_payItem.setOnClickListener(detailListener);

                img_check.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (Utils.isFastDoubleClick())
                            return;
                        if (item.isChoose()) {//由选中，移除
                            item.setChoose(false);
                            chooseNum = chooseNum - item.getPreparePayNum();//移除缴费项中
                            addPrice = SubtractTwoValue(addPrice,item.getPreparePay());//移除总计金额
                            item.setPreparePay(0);//当前item的预计支付金额置为0
                            item.setPreparePayNum(0);//当前item的支付项置为0
                        } else {
                            item.setChoose(true);
                            item.setPreparePay(item.getNeedpayMoney());
                            item.setPreparePayNum(item.getNeedPayNum());
                            chooseNum = chooseNum + item.getPreparePayNum();
                            addPrice = AddTwoValue(addPrice,item.getPreparePay());
                        }
                        item.setChooseType(0);//choosetype置0，表示缴费类型为全部
                        if (item.getMonthList() != null)
                            item.getMonthList().clear();
                        setCheckAll();
                    }
                });

            }
        };
        recyclerView.setAdapter(recycleCommonAdapter);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(true);
            }
        });
        getData(false);
    }

    /**
     * 点击年列表
     *
     * @param item 年缴费对象
     */
    private void clickItem(PaymentBean.DataBean.YearPaymentBean item) {
        if (item.getNeedPayNum() == 0)
            return;
        Intent in = new Intent(TenementYearActivity.this, TenementMonthActivity.class);
        in.putExtra("title", item.getYearTitle());//标题
        in.putExtra("year", item.getYear());//年
        if (item.getChooseType() == 0)//如果没有type应付项，将全部应付项赋值过去
            item.setTypeNeedPayNum(item.getNeedPayNum());
        in.putExtra("typeNeedPayNum", item.getTypeNeedPayNum());//筛选后对应的type项应缴费总数
        in.putExtra("addPrice", item.getPreparePay());//传递总金额
        in.putExtra("chooseNum", item.getPreparePayNum());//已勾选的缴费项目数
        //注意此处修改：仅当列表不为空,且未点击左边全选项时
        if (item.getMonthList() != null && item.getMonthList().size() != 0) {
            in.putExtra("monthList", (Serializable) item.getMonthList());
        }
        in.putExtra("typePsi", item.getChooseType());//记录的筛选type
        startActivityForResult(in, 101);
    }

    /**
     * 获取物业缴费清单
     */
    private void getData(final boolean isRefresh) {
        if (!isRefresh)
            showLoading();
        enqueue(createCallService(ServiceService.class).getPaymentInfo(user.getEnterpriseId()), new RetrofitCallbackListener<PaymentBean>() {
            @Override
            public void onSuccess(Call<PaymentBean> call, PaymentBean tenementMonthBean) {
                misLoading();
                swipeRefresh.setRefreshing(false);
                load_view.loadComplete();
                if(tenementMonthBean.getData()==null)return;
                yearPaymentBeanList.clear();
                if (tenementMonthBean.getData().getYearPayment() != null && tenementMonthBean.getData().getYearPayment().size() > 0) {
                    yearPaymentBeanList.addAll(tenementMonthBean.getData().getYearPayment());
                    recycleCommonAdapter.notifyDataSetChanged();
                } else {
                    load_view.loadCompleteNoData(R.mipmap.none_data_icon,"暂无缴费项目");
                }
                allPrice = 0;
                allNum = 0;
                for (int i = 0, len = yearPaymentBeanList.size(); i < len; i++) {
                    allPrice = allPrice + yearPaymentBeanList.get(i).getNeedpayMoney();
                    allNum = allNum + yearPaymentBeanList.get(i).getNeedPayNum();
                }
                //此处由于刷新，所以要求统计数据置0，底部栏统计清空
                chooseNum = 0;
                addPrice = 0;
                setCheckAll();
                txAddress.setText(tenementMonthBean.getData().getRoomDetail() + "");
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(msg);
                misLoading();
                swipeRefresh.setRefreshing(false);
                if(yearPaymentBeanList.size()==0)load_view.loadCompleteNoData(R.mipmap.none_data_icon,"暂无缴费项目");
            }
        });
    }


    @OnClick({R.id.img_check, R.id.tx_goPay})
    public void onClick(View view) {
        if (Utils.isFastDoubleClick())
            return;
        switch (view.getId()) {
            case R.id.img_check:
                if (chooseNum != allNum) {
                    chooseNum = allNum;
                    addPrice = allPrice;
                    setChooseDo(true);
                } else {
                    chooseNum = 0;
                    addPrice = 0;
                    setChooseDo(false);
                }
                setCheckAll();
                break;
            case R.id.tx_goPay:
                if(yearPaymentBeanList.size()==0)return;
                if (chooseNum == 0) {
                    ToastUtil.show(this, "请选择缴费项目");
                    return;
                }
                goPay();
                break;
            default:
                break;
        }
    }

    /**
     * 數據變化處理底部，刷新列表
     */
    private void setCheckAll() {
        txChooseChild.setText("已选" + chooseNum + "项");
        txNeedPay.setText(Html.fromHtml("<font color=#666666>" + "合计：" + "</font>"
                + "<font color=#ff6e0b>" + "¥" + decimalFormat.format(addPrice) + "</font>"));
        recycleCommonAdapter.notifyDataSetChanged();
        if (chooseNum == allNum && chooseNum != 0) {
            imgCheck.setImageResource(R.mipmap.check_theme);
        } else {
            imgCheck.setImageResource(R.mipmap.un_check_gray);
        }
    }

    /**
     * 设置全选or全部选
     */
    private void setChooseDo(boolean choose) {
        for (int i = 0, len = yearPaymentBeanList.size(); i < len; i++) {
            PaymentBean.DataBean.YearPaymentBean yearPaymentBean = yearPaymentBeanList.get(i);
            yearPaymentBean.setChoose(choose);
            if (choose) {
                yearPaymentBean.setPreparePay(yearPaymentBean.getNeedpayMoney());
                yearPaymentBean.setPreparePayNum(yearPaymentBean.getNeedPayNum());
            } else {
                yearPaymentBean.setPreparePay(0);
                yearPaymentBean.setPreparePayNum(0);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null || resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case 101://修改选中月份列表
                List<TenementMonthBean.DataBean> lst = (List<TenementMonthBean.DataBean>) data.getSerializableExtra("monthList");
                int num = data.getIntExtra("num", 0);
                double money = data.getDoubleExtra("money", 0);
                int choosePsi = data.getIntExtra("typePsi", 0);
                int typeNeedPayNum = data.getIntExtra("typeNeedPayNum", 0);
                if (yearPaymentBeanList == null || lst == null)
                    return;
                //数据传递使用的month列表
                PaymentBean.DataBean.YearPaymentBean yearPaymentBean = yearPaymentBeanList.get(clickPosi);
                if (yearPaymentBean.getMonthList() != null)
                    yearPaymentBean.getMonthList().clear();
                yearPaymentBean.setMonthList(lst);
                if (num > 0)
                    yearPaymentBean.setChoose(true);
                else
                    yearPaymentBean.setChoose(false);
                //年列表变化
                chooseNum = chooseNum - yearPaymentBean.getPreparePayNum() + num;
                addPrice = AddTwoValue(SubtractTwoValue(addPrice,yearPaymentBean.getPreparePay()),money);
                yearPaymentBeanList.get(clickPosi).setPreparePayNum(num);
                yearPaymentBeanList.get(clickPosi).setPreparePay(money);
                yearPaymentBeanList.get(clickPosi).setChooseType(choosePsi);
                yearPaymentBeanList.get(clickPosi).setTypeNeedPayNum(typeNeedPayNum);

                setCheckAll();
                break;
            case 102://支付成功回调
                swipeRefresh.setRefreshing(true);
                getData(false);
                break;
        }
    }

    /**
     * 去支付
     */
    private void goPay() {
        List<String> idList = new ArrayList<>();
        List<String> yearList = new ArrayList<>();
        for (int i = 0, len = yearPaymentBeanList.size(); i < len; i++) {
            PaymentBean.DataBean.YearPaymentBean yearPaymentBean = yearPaymentBeanList.get(i);
            if (yearPaymentBean.getPreparePayNum() > 0) {
                if (yearPaymentBean.getPreparePayNum() == yearPaymentBean.getNeedPayNum()) {
                    yearList.add(yearPaymentBean.getYear() + "");
                } else {
                    List<TenementMonthBean.DataBean> monthList = yearPaymentBean.getMonthList();
                    for (int j = 0, lenJ = monthList.size(); j < lenJ; j++) {
                        TenementMonthBean.DataBean month = monthList.get(j);
                        List<TenementMonthBean.DataBean.BillMonthListBean> billMonthListBeen = month.getBillMonthList();
                        for (int z = 0, lenZ = billMonthListBeen.size(); z < lenZ; z++) {
                            if (billMonthListBeen.get(z).isChoose()) {
                                idList.add(billMonthListBeen.get(z).getId());
                            }
                        }
                    }
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < idList.size(); i++) {
            if (i != 0) {
                sb.append(",");
            }
            sb.append(idList.get(i));
        }
        String ids = sb.toString();
        StringBuilder sb2 = new StringBuilder();
        for (int i = 0; i < yearList.size(); i++) {
            if (i != 0) {
                sb2.append(",");
            }
            sb2.append(yearList.get(i));
        }
        String years = sb2.toString();
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("subId", subId);
        params.put("totalPrice", decimalFormat.format(addPrice) + "");
        if (!TextUtils.isEmpty(ids))
            params.put("idList", ids);
        if (!TextUtils.isEmpty(years))
            params.put("yearList", years);
        params.put("enterpriseId",user.getEnterpriseId());
        params.put("userId",user.getEnterpriseAdminId());
        enqueue(createCallService(ServiceService.class).commitTenementOrder(params), new RetrofitCallbackListener<TenementPayOrderBean>() {
            @Override
            public void onSuccess(Call<TenementPayOrderBean> call, TenementPayOrderBean tenementMonthBean) {
                misLoading();
                if (tenementMonthBean.getData() == null)
                    return;
                Intent in = new Intent(TenementYearActivity.this, TenementPayActivity.class);
                in.putExtra("bean", tenementMonthBean.getData());
                in.putExtra("busId",busId);
                startActivityForResult(in, 102);
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(msg);
                misLoading();
            }
        });
    }

}
